package com.bt7274.scheduler;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bt7274.mapper.*;
import com.bt7274.pojo.*;
import com.bt7274.service.PermanentPromotionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 常驻活动定时任务
 *
 * @return null
 * @author galland
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class PermanentPromotionScheduler {

    private final PermanentPromotionService permanentPromotionService;
    private final PeerMapper peerMapper;
    private final PtRecordMapper ptRecordMapper;
    private final UserExpMapper userExpMapper;
    private final TransferHistoryMapper transferHistoryMapper;


    /**
     * 每天凌晨0点5分重置连续签到（针对中断签到的用户）
     */
    @Scheduled(cron = "0 5 0 * * ?")
    @Transactional
    public void resetBrokenConsecutiveCheckIns() {
        log.info("开始检查并重置中断的连续签到记录...");

        // 这个任务主要是为了清理数据，实际的连续签到判断在签到时进行
        // 可以在这里做一些统计或清理工作

        log.info("连续签到记录检查完成");
    }

    /**
     * 每天凌晨3点生成常驻活动统计报告
     */
    @Scheduled(cron = "0 0 3 * * ?")
    public void generatePermanentPromotionReport() {
        log.info("开始生成常驻活动统计报告...");

        try {
            // 统计昨天的签到人数
            QueryWrapper<UserDailyCheckIn> checkInWrapper = new QueryWrapper<>();
            checkInWrapper.eq("check_in_date", LocalDateTime.now().minusDays(1).toLocalDate());
            Long dailyCheckInCount = checkInMapper.selectCount(checkInWrapper);

            // 统计活跃做种用户数
            QueryWrapper<PtRecord> seedingWrapper = new QueryWrapper<>();
            seedingWrapper.eq("seeding", 1)
                    .groupBy("user_id");
            Long activeSeedersCount = ptRecordMapper.selectCount(seedingWrapper);

            // 统计本月达成的里程碑数
            QueryWrapper<UserMilestoneRecord> milestoneWrapper = new QueryWrapper<>();
            milestoneWrapper.ge("achieved_time", LocalDateTime.now().withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0));
            Long monthlyMilestonesCount = milestoneRecordMapper.selectCount(milestoneWrapper);

            log.info("常驻活动统计 - 昨日签到: {}人, 活跃做种: {}人, 本月里程碑: {}个",
                    dailyCheckInCount, activeSeedersCount, monthlyMilestonesCount);

            // TODO: 可以将报告保存到数据库或发送给管理员

        } catch (Exception e) {
            log.error("生成常驻活动统计报告失败", e);
        }

        log.info("常驻活动统计报告生成完成");
    }

    private final UserDailyCheckInMapper checkInMapper;
    private final UserMilestoneRecordMapper milestoneRecordMapper;
}